<?php
	include'Utils.php';
	/**
	 * 
	 * Class used to handle even of Subjects
	 * @author NguyenBo
	 *
	 */
	class SubjectsController extends AppController{
		
		/**
		 * List components used in this class
		 */
		public $components = array('CenterInfo', 'Schedule', 'Video', 'FacultySubject', 'Lib', 'Course');
		
		/**
		 * Admin Method:  Get all data from Subjects tables
		 */
		function manageListSubject(){
			// Check session and redirect to login page
			Utils::checkSession($this);
			$this->set('admin', '1');
			
			// Get common information
			$centerInfo = $this->CenterInfo->getInfo();
			$this->set('center_info', $centerInfo);
			// Get all record
			$this->set('subjects', $this->Subject->find('all'));
				
		}
		
		/**
		 * Admin Method: get specified record and display data on input screen
		 */
		function editSubject(){
			// Check session and redirect to login page
			Utils::checkSession($this);
			$this->set('admin', '1');
			
			// Main process
			$isBack = isset($_POST['isBack']) ? $_POST['isBack'] : "";
			$this->set('isBack', $isBack);
			// Get common information
			$centerInfo = $this->CenterInfo->getInfo();
			$this->set('center_info', $centerInfo);
			If($isBack == ""){
				// Get post data
				$subId = isset($_POST["id"]) ? $_POST["id"] : "";
				// If subid not set ====> redirect to list subject page
				If ($subId == "") {
					$this->redirect(array(
						'controller' => 'Subjects',
						'action' => 'manageListSubject'
					));
				}
				// Get subject with specified id
				$this->set('subject', $this->Subject->findAllBysub_id($subId));
				$video = $this->Video->getMainVideo($subId);
				$this->set('video', $video[0]);
				$this->set('subjects', $this->Subject->find('all'));
			}else{
				$centerInfo = array();
				$subId = isset($_POST['subId']) ? $_POST['subId'] : "";
				
				// If subid not set ====> redirect to list subject page
				If ($subId == "") {
					$this->redirect(array(
						'controller' => 'Subjects',
						'action' => 'manageListSubject'
					));
				}
				
				$subName = isset($_POST['subName']) ? Utils::encodeString($_POST['subName']) : "";
				$subDescript = isset($_POST['subDescript']) ? Utils::encodeString($_POST['subDescript']) : "";
				$confirmType = isset($_POST['confirmType']) ? $_POST['confirmType'] : "";
				$imageName = isset($_POST["imageName"]) ? $_POST["imageName"] : "";
				$oldSubName = isset($_POST["oldSubName"]) ? $_POST["oldSubName"] : "";
				$subFee = isset($_POST['subFee']) ? $_POST['subFee'] : "";
				$video = $this->Video->getMainVideo($subId);
				$this->set("subName", $subName);
				$this->set("subDescript", $subDescript);
				$this->set("videoId", $video[0]["Video"]["m_youtube_id"]);
				$this->set("confirmType", $confirmType);
				$this->set("subId", $subId);
				$this->set("imageName", $imageName);
				$this->set("oldSubName", $oldSubName);
				
				// Delete temp uploaded file
				If(($imageName != "")){
					if(file_exists("temp/upload_temp/".$imageName)){
						unlink("temp/upload_temp/".$imageName);
					}
				}
			}
		}
		
		/**
		 * Admin Method: display input subject page
		 */
		function inputSubject(){
			
			// Check session and redirect to login page
			Utils::checkSession($this);
			$this->set('admin', '1');
			
			// Get common information
			$centerInfo = $this->CenterInfo->getInfo();
			$this->set('center_info', $centerInfo);
			
			// Get POST data and display
			$subName = isset($_POST["subName"]) ? Utils::encodeString($_POST["subName"]) : "";
			$subDesript = isset($_POST["subDescript"]) ? Utils::encodeString($_POST["subDescript"]) : "";
			$videoId = isset($_POST['videoId']) ? $_POST['videoId'] : "";
			$fileName = isset($_POST['fileName']) ? $_POST['fileName'] : "";
			$subFee = isset($_POST['subFee']) ? $_POST['subFee'] : "";
			$this->set('subName', $subName);
			$this->set('videoId', $videoId);
			$this->set('subDescript', $subDesript);
			$this->set('subFee', $subFee);
			
			// Delete temp uploaded file
			If(($fileName != "")  && (file_exists("temp/upload_temp/".$imageName))){
				unlink("temp/upload_temp/".$fileName);
			}
		}
		
		/**
		 * Admin Method: display confirm edit/regist page
		 */
		function confirmSubject(){
			
			// Check session and redirect to login page
			Utils::checkSession($this);
			$this->set('admin', '1');
			
			//Get POST data and display on page
			$subId = isset($_POST["subId"]) ? $_POST["subId"] : "";
			$subName = isset($_POST["subName"]) ? Utils::encodeString($_POST["subName"]) : "";
			$subDesript = isset($_POST["subDescript"]) ? Utils::encodeString($_POST["subDescript"]) : "";

			$confirmType = isset($_POST["confirmType"]) ? $_POST["confirmType"] : "";
			$videoId = isset($_POST["video_id"]) ? $_POST["video_id"] : "";
			$fileName = isset($_POST["fileName"]) ? $_POST["fileName"] : "";
			$oldSubName = isset($_POST['oldSubName']) ? Utils::encodeString($_POST['oldSubName']) : "";
			$subFee = isset($_POST['subFee']) ? $_POST['subFee'] : "";
			
			// Set page property
			$this->set('confirmType', $confirmType);
			$this->set('subId',$subId);
			$this->set('subName', $subName);
			$this->set('subDescript', $subDesript);
			$this->set('videoId', $videoId);
			$this->set('oldSubName', $oldSubName);
			$this->set('subFee', $subFee);
			
			if (isset($_POST["subOldImage"])){
				$this->set('subOldImage', $_POST["subOldImage"]);
			}
				
			if(isset($_FILES['file'])){
				$this->set('fileName', $_FILES["file"]["name"]);
				
				// Upload temp file
				move_uploaded_file($_FILES["file"]["tmp_name"],
				"temp/upload_temp/" .$_FILES["file"]["name"]);
				$this->set('fileChange', '1');
				
			}else{
				$this->set("fileName", $fileName);
				$this->set('fileChange', '0');
			}
			// Get common information
			$centerInfo = $this->CenterInfo->getInfo();
			$this->set('center_info', $centerInfo);
			
		}
		
		/**
		 * Admin Method: display regist page
		 */
		function registSubject(){
			
			// Check session and redirect to login page
			Utils::checkSession($this);
			$this->set('admin', '1');
			
			// Get common information
			$centerInfo = $this->CenterInfo->getInfo();
			$this->set('center_info', $centerInfo);
			
			// Get process type
			$registType = isset($_GET["type"]) ? $_GET["type"] : "";
			if ($registType == ""){
				$this->redirect(array(
					'controller' => 'Subjects',
					'action' => 'manageListSubject'
				));
			}
			
			if($registType == "insert"){ // Regist new record into subjects table
				
				$this->Subject->create();
				
				$subName = isset($_POST["subName"]) ? Utils::encodeString($_POST["subName"]) : "";
				$subDesript = isset($_POST["subDescript"]) ? Utils::encodeString($_POST["subDescript"]) : "";
				$imageName = isset($_POST["imageName"]) ? $_POST["imageName"] : "";
				$videoId = isset($_POST["videoId"]) ? $_POST["videoId"] : "";
				$subFee = isset($_POST["subFee"]) ? $_POST["subFee"] : 0;
				
				// If data not set ==> redirect to list page
				if($subName == "" || $subDesript == "" || $imageName == "" || $videoId == ""){
					$this->redirect(array(
						'controller' => 'Subjects',
						'action' => 'manageListSubject'
					));
				}
				
				// Create saved request data
				$this->request->data['sub_id'] = null;
				$this->request->data['sub_name'] = $subName;
				$this->request->data['sub_descript'] = $subDesript;
				$this->request->data['sub_image'] = $imageName;
				$this->request->data['sub_fee'] = $subFee;
				
				if($this->Subject->save($this->request->data)){
					$newestSub = $this->Subject->findAllBysub_name($subName);
					// regist video
					$this->request->data['m_video_id'] = null;
					$this->request->data['m_video_sub_id'] = $newestSub[0]['Subject']['sub_id'];
					$this->request->data['m_youtube_id'] = $videoId;
					$this->request->data['m_video_title'] = null;
					$this->request->data['m_video_descript'] = null;
					$this->request->data['m_is_main_video'] = '1';
					 
					$this->Video->registVideoForNewSubject($this->request->data);
					// Create root folder for library
					mkdir("sub_libs/".$newestSub[0]['Subject']['sub_id']);
					
					// Move image to image folder
					if (file_exists("temp/upload_temp/".$imageName)){
						copy("temp/upload_temp/".$imageName,
						"sub/" .$imageName);
						
						unlink("temp/upload_temp/".$imageName);
					}
					$this->redirect(array('action' => 'manageListSubject', null));
				}else{
					$this->set('result', 'fail');
				}
			}else{ // Update specified record in subjects table
				
				// get POST subject id
				$subId = isset($_POST["subId"]) ? $_POST["subId"] : "";
				
				// If subject id is not set ==> redirect to list page
				if($subId == ""){
					$this->redirect(array(
						'controller' => 'Subjects',
						'action' => 'manageListSubject'
					));
				}
				
				// Get POST data
				$imageName = isset($_POST["imageName"]) ? $_POST["imageName"] : "";
				$videoId = isset($_POST["videoId"]) ? $_POST["videoId"] : "";
				$subName = isset($_POST["subName"]) ? Utils::encodeString($_POST["subName"]) : "";
				$fileChange = isset($_POST["isFileChange"]) ? $_POST["isFileChange"] : "";
				$subDesript = isset($_POST["subDescript"]) ? $_POST["subDescript"] : "";
				$subDesript = Utils::encodeString($subDesript);
				$subFee = isset($_POST["subFee"]) ? $_POST["subFee"] : 0;
				
				// Delete old image
				if($fileChange == '1'){
					$this->deleteOldImage($subId);
				}
				$dataNeedToSave = array(
					                'Subject.sub_name' => "'" . $subName . "'",
					                'Subject.sub_descript' => "'". $subDesript . "'",
									'Subject.sub_image' => "'" . $imageName . "'",
									'Subject.sub_fee' => "'" . $subFee . "'"
				);
				$saveCondition = array('Subject.sub_id' => $subId);
				if ($this->Subject->updateAll($dataNeedToSave, $saveCondition)) {
					$this->Video->deleteMainVideo($this->request->data['subId']);
					$this->request->data['m_video_id'] = null;
					$this->request->data['m_video_sub_id'] = $subId;
					$this->request->data['m_youtube_id'] = $videoId;
					$this->request->data['m_video_title'] = null;
					$this->request->data['m_video_descript'] = null;
					$this->request->data['m_is_main_video'] = '1';
					
					// Move image to image folder
					if (file_exists("temp/upload_temp/".$imageName)){
						copy("temp/upload_temp/".$imageName,
						"sub/" .$imageName);
						unlink("temp/upload_temp/".$imageName);
					}
					$this->redirect(array('action' => 'manageListSubject', null));
				} else {
					$this->Session->setFlash('Unable to update schedule.');
				}
			}
		}
		
		/**
		 * Admin Method: Delete subject and display list
		 */
		function deleteSubject(){
			
			// Check session and redirect to login page
			Utils::checkSession($this);
			$this->set('admin', '1');
			
			$id = isset($_POST['id']) ? $_POST['id'] : "";
			if ($id == ""){
				$this->redirect(array(
					'controller' => 'Subjects',
					'action' => 'manageListSubject'
				));
			}
			
			// Delete faculty subject
			$this->FacultySubject->deleteAllBySubId($id);
			
			// Delete libraries
			$this->Lib->deleteAllBySubId($id);
			
			// Delete Videos
			$this->Video->deleteAllBySubId($id);
			
			// Delete lib folder
			rmdir("sub_libs/" . $id);
			
			$subject = $this->Subject->find('all', array(
				'condition' => array ('Subject.sub_id' => $id)
			));
			// Delete image
			unlink("sub/" . $subject[0]["Subject"]['sub_image']);
			
			if ($this->Subject->deleteAll(array('Subject.sub_id' => $id), false)) {
				// Delete specified record in subjects table
				$this->redirect(array('action' => 'manageListSubject'));
			}else{
				echo "fail";die;
			}
		}
		
		/**
		 * Front End Method: display list subjects
		 */
		function listSubject(){
			
			// Get common information
			$centerInfo = $this->CenterInfo->getInfo();
			$this->set('center_info', $centerInfo);
			
			// Get list Course
			$courses = $this->Course->getAll();
			$this->set('courses', $courses);
			
			// Get list Subjects
			$this->set('subjects', $this->Subject->find('all'));
			
		}
		
		/**
		 * Front End Method: Dispslay subject details page
		 */
		function detailSubject(){
			
			// Get common information
			$centerInfo = $this->CenterInfo->getInfo();
			$this->set('center_info', $centerInfo);
			
			// Get list Course
			$courses = $this->Course->getAll();
			$this->set('courses', $courses);
			
			// Get request value
			$sub_id = isset($_GET['sub_id']) ? $_GET['sub_id'] : "";
			if($sub_id == "")
				$this->redirect(array(
					'action' => 'index'
				));
			
			// Get subject by id
			$subject = $this->Subject->findAllBysub_id($sub_id);
			$this->set('subject', $subject);
			
			// Get all subjects
			$subjects = $this->Subject->find('all');
			$this->set('subjects', $subjects);
			
			$videos = $this->Video->getMainVideo($sub_id);
			$this->set('video', $videos);
			
			// Set another information
			$this->set('selectedId', $sub_id);
			
			// Set schedules information
			$schedules = $this->Schedule->getScheduleBySubId($sub_id);
			$outputSchedules = array();
			foreach ($schedules as $schedule):
				$dayOfWeek = "";
				$dayOfWeek = Utils::getDayofWeek($schedule['Schedule']['m_sdl_week_day']);
				$schedule['Schedule']['m_sdl_week_day'] = $dayOfWeek;
				array_push($outputSchedules, $schedule);
			endforeach;
			$this->set('schedules', $outputSchedules);
		}
		
		/**
		 * 
		 * Function used to check if subject already exist
		 * @param String $subname
		 * @param String $videoId
		 * @param String $subDesript
		 */
		public function checkExistSubject(){
			$subname = $_POST['sub_name'];
			$confirmType = $_POST['confirm_type'];
			$oldSubName = $_POST['old_sub_name'];
			
			/* Check file exist */
			if (isset($_POST['image_name'])){
				$imageName = $_POST['image_name'];
				if (strlen($imageName) > 0){
				
					/* Move image of this subject to delete_temp before checking
					 * In order to allow user post same image file name for this faculty
					 */
					if ((isset($_POST['subOldImage'])) && (strlen($_POST['subOldImage']) > 0)){
						if (file_exists("sub/".$_POST['subOldImage'])){
							copy("sub/".$_POST['subOldImage'],
							 	"temp/delete_temp/".$_POST['subOldImage']);
							unlink("sub/".$_POST['subOldImage']);
						}
					}
					
					$fileError = false;
					if (file_exists("sub/".$imageName)){
						$fileError = true;
					}
					
					if ((isset($_POST['subOldImage'])) && (strlen($_POST['subOldImage']) > 0)){
						copy("temp/delete_temp/".$_POST['subOldImage'],
					 	"sub/".$_POST['subOldImage']);
						unlink("temp/delete_temp/".$_POST['subOldImage']);
					}
					
					if ($fileError == true){
						echo "fileError"; 
						die;
					}
				}
			}
			
			if($confirmType == 'insert' || ($confirmType == 'update' && $subname != $oldSubName)){
				$count = $this->Subject->find('count', array(
					'conditions' => array('Subject.sub_name' => $subname)
				));
				if($count > 0) {
					echo "Môn học đã tồn tại"; die;
				}else{
					echo ""; die;
				}
			}else{
				echo "";die;
			}
		}
		
		/**
		 * Function used to delete old image of subject
		 * @param unknown_type $subId
		 */
		public function deleteOldImage($subId){
			$subject = $this->Subject->findAllBysub_id($subId);
			$imageName = $subject[0]["Subject"]["sub_image"];
			if(file_exists("sub/".$imageName)){
				unlink("sub/".$imageName);
			}
		}
		
	}
?>